<template>
  <div class="view-body">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" :label-width="labelWidth"
      :disabled="type=='watch'?true:false" class="demo-ruleForm">
      <div class="title_view">活动基本信息</div>
      <el-form-item label="管辖区域:" prop="areaId">
        <el-select v-model="ruleForm.areaId" filterable placeholder="请选择" clearable :style="{width: inputWidth}"
          @change="areaChange" :disabled="status==1||type=='add'?false:true">
          <el-option v-for="dict in areaLs" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="活动名称:" prop="name">
        <el-input type="text" v-model="ruleForm.name" placeholder="请输入活动名称" :style="{width: inputWidth}"></el-input>
      </el-form-item>
      <el-form-item label="活动时间:" prop="date">
        <el-date-picker v-model="ruleForm.date" type="datetimerange" value-format="yyyy-MM-dd HH:mm"
          format="yyyy-MM-dd HH:mm" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          :style="{width: inputWidth}">
        </el-date-picker>
      </el-form-item>
      <div class="title_view">活动规则</div>
      <el-form-item label="激励规则:" prop="incentiveRule">
        <el-select v-model="ruleForm.incentiveRule" filterable placeholder="请选择" clearable :style="{width: inputWidth}">
          <el-option v-for="dict in incentiveRuleLs" :key="dict.id" :label="dict.value" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="积分类型:" prop="incentiveType">
        <el-select v-model="ruleForm.incentiveType" filterable placeholder="请选择" clearable :style="{width: inputWidth}">
          <el-option v-for="dict in incentiveTypeLs" :key="dict.id" :label="dict.value" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="需达到交易额:" prop="limitOrderMoney">
        <el-input v-model="ruleForm.limitOrderMoney" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">元</template></el-input>
      </el-form-item>
      <el-form-item label="激励比例:" prop="incentiveValue" v-if="ruleForm.incentiveRule==1">
        <el-input v-model="ruleForm.incentiveValue" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">%</template></el-input>
      </el-form-item>
      <el-form-item label="激励数额:" prop="incentiveValue" v-if="ruleForm.incentiveRule==2">
        <el-input v-model="ruleForm.incentiveValue" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">{{ruleForm.incentiveType==2?'椰分':'CoCo'}}</template></el-input>
      </el-form-item>
      <el-form-item label="每日活动名额:" prop="dailyNum">
        <el-input v-model="ruleForm.dailyNum" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">名</template></el-input>
      </el-form-item>
      <el-form-item label="每日用户参与次数:" prop="userDailyNum">
        <el-input v-model="ruleForm.userDailyNum" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">次</template></el-input>
      </el-form-item>
      <el-form-item label="用户参与总次数:" prop="userTotalNum">
        <el-input v-model="ruleForm.userTotalNum" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">次</template></el-input>
      </el-form-item>
      <el-form-item label="封顶激励值:" prop="incentiveTopValue" v-if="ruleForm.incentiveRule==1">
        <el-input v-model="ruleForm.incentiveTopValue" placeholder="请输入" :style="{width: inputWidth}"><template
            slot="append">{{ruleForm.incentiveType==2?'椰分':'CoCo'}}</template></el-input>
      </el-form-item>
      <div class="title_view">用户规则</div>
      <el-form-item label="用户规则:" prop="incentiveUserRule">
        <el-radio v-model="ruleForm.incentiveUserRule" label="1">平台实名用户</el-radio>
        <el-radio v-model="ruleForm.incentiveUserRule" label="2">当天实名用户</el-radio>
      </el-form-item>
      <div class="title_view">活动店铺</div>
      <div>
        <span style="font-size: 14px">参与活动店铺列表：</span>
        <el-button size="small" type="primary" style="margin-right: 20px" @click="addShopView"
          :disabled="ruleForm.areaId==''?true:false">添加</el-button>
        <div class="el_table">
          <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="行业类型：" prop="shopTypeId">
              <!-- <el-select v-model="queryParams.shopTypeId" placeholder="全部" size="small" style="width: 240px">
                <el-option v-for="item in incentiveTypeLs" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select> -->
              <el-cascader filterable :options="typeLs" @change="handleChange" v-model="shopTypeIdLs" size="small"
                :props="{ value: 'id',label: 'label',children: 'children', checkStrictly: true}" />
            </el-form-item>
            <el-form-item label="神椰店铺行业：" prop="shenyeIndustryId">
              <el-select filterable v-model="queryParams.shenyeIndustryId" placeholder="请选择" size="small"
                style="width: 240px">
                <el-option v-for="item in shenyeIndustryList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商户级别：" prop="merchantLevel">
              <el-select filterable v-model="queryParams.merchantLevel" placeholder="全部" size="small"
                style="width: 240px">
                <el-option v-for="item in merchantLevelList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关键字：" prop="keyword">
              <el-input v-model="queryParams.keyword" placeholder="店铺名称/商户账号名称/手机号" clearable size="small"
                style="width: 240px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery" size="small">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery" size="small">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="danger" style="margin-bottom: 20px" size="small" :disabled="productIds.length==0?true:false"
            @click="deleteView(null)">
            批量删除</el-button>
          <el-table ref="multipleTable" v-loading="loading" :data="tableList" stripe border row-key="id"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" :reserve-selection="true" width="55" fixed="left">
            </el-table-column>
            <el-table-column label="序号" align="center" type="index" width="64px" />
            <el-table-column label="店铺名称" align="center" prop="shopName" :show-overflow-tooltip="true" />
            <el-table-column label="商户账户名称" align="center" prop="merchantName" :show-overflow-tooltip="true" />
            <el-table-column label="手机号" align="center" prop="phone" />
            <el-table-column label="管辖区域" align="center" prop="govAreaName" />
            <el-table-column label="所属地区" align="center" prop="merchantArea" />
            <el-table-column label="行业类型" align="center" prop="shopTypeName" />
            <el-table-column label="神椰店铺行业" align="center" prop="shenyeIndustryName" />
            <el-table-column label="商户级别" align="center" prop="merchantLevel" />
            <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="deleteView(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :autoScroll="false"
            :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
        </div>
      </div>
    </el-form>
    <el-button type="warning" @click="submitForm('ruleForm',1)" :loading="sumitLoadingOne"
      v-if="(status==1&&type!='watch')||type=='add'">存为草稿
    </el-button>
    <el-button type="primary" @click="submitForm('ruleForm',2)" :loading="sumitLoading" v-if="type!='watch'">保存提交
    </el-button>
    <el-button @click="handleClose('ruleForm')">取消</el-button>
    <AddShop ref="dialog" @refresh="getList"></AddShop>
  </div>
</template>
<script>
  // components
  import Loading from '@/components/Loading/index'
  // api
  import {
    shopTypeTree,
  } from "@/api/merchants";
  import {
    industrySelect,
  } from "@/api/merchants/merchantsAudit";
  import {
    areaList,
    shopTempInit,
    shopTempList,
    activityShopTempDelete,
    shenyeIncentiveActivityAdd,
    shenyeIncentiveActivityEdit,
    incentiveActivityDetail,
    shopListWatch,
  } from '@/api/consumeIncentiveManagement/incentiveActivities'
  import AddShop from "./components/addShop";
  export default {
    components: {
      Loading,
      AddShop
    },
    props: {
      visible: Boolean,
      id: String,
      pathType: String,
    },
    data() {
      var inspectLimitOrderMoney = (rule, value, callback) => { //需达到交易额校验
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请输入大于0且最多保留两位小数的数值'));
        } else {
          return callback()
        }
      };
      var inspectIncentiveValue = (rule, value, callback) => { //激励比例/激励数额 校验
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请输入大于0且最多保留两位小数的数值'));
        } else {
          return callback()
        }
      };
      var inspectDailyNum = (rule, value, callback) => { //每日活动名额校验
        let regNumber = /(^[1-9]\d*$)/; //大于0的正整数
        if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于0的整数'));
        } else {
          return callback()
        }
      };
      var inspectUserDailyNum = (rule, value, callback) => { //每日用户参与次数校验
        let regNumber = /(^[1-9]\d*$)/; //大于0的正整数
        if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于0的整数'));
        } else {
          return callback()
        }
      };
      var inspectUserTotalNum = (rule, value, callback) => { //用户参与总次数校验
        let regNumber = /(^[1-9]\d*$)/; //大于0的正整数
        if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于0的整数'));
        } else {
          return callback()
        }
      };
      var inspectIncentiveTopValue = (rule, value, callback) => { //封顶激励值 校验
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (regNumber.test(value) == false || value == '0.00' || value == '0.0') {
          return callback(new Error('请输入大于0且最多保留两位小数的数值'));
        } else {
          return callback()
        }
      };
      return {
        loading: false,
        sumitLoading: false, //保存loaidng
        sumitLoadingOne: false, //草稿loading
        labelWidth: '160px',
        inputWidth: '340px',
        type: '', // add :新增  edit: 编辑  watch: 查看
        areaLs: [], //管辖区域
        incentiveRuleLs: [], //激励规则字典
        incentiveTypeLs: [], //激励积分类型字典
        typeLs: [], //行业类型
        shopTypeIdLs: [],
        shenyeIndustryList: [], //神椰店铺行业列表
        merchantLevelList: [{
            id: '',
            value: '全部'
          },
          {
            id: '1',
            value: '未使用商家'
          },
          {
            id: '2',
            value: '合作商家'
          },
          {
            id: '3',
            value: '普通商家'
          },
          {
            id: '4',
            value: '诚信商家'
          },
          {
            id: '5',
            value: '金牌商家'
          },
        ],
        // 总条数
        // total: 0,
        // 表格数据
        tableList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          incentiveActivityId: '', //激励活动id
          keyword: '', //关键字(店铺名称/商户账号名称/手机号)
          merchantLevel: '', //商户级别 1 未使用商家 2 合作商家 3普通商家 4诚信商家 5金牌商家
          shenyeIndustryId: '', //神椰店铺行业id
          shopTypeId: '', //行业类型id
          shopTypeParentId: '', //行业父类型id
        },
        productIds: [], // 选中数组
        shopIdList: [], //过滤店铺id列表
        status: '', //状态 1-草稿 2-待开始 3-进行中 4-已结束
        ruleForm: {
          date: [],
          areaId: '', //管辖区域id（新增必填）
          dailyNum: '', //每日活动名额
          endTime: '', //活动结束时间
          id: '', //激励活动id（编辑必填）
          incentiveRule: '', //激励规则 1-按比例激励 2-固定金额激励 shenye_incentive_rule
          incentiveTopValue: '', //封顶激励值
          incentiveType: '', //激励积分类型 1-CoCo 2-椰分 shenye_incentive_type	
          incentiveUserRule: '1', //用户规则 1-平台实名用户 2-当天实名用户 BeeShenyeIncentiveUserRuleEnum
          incentiveValue: '', //激励比例/激励数额
          limitOrderMoney: '', //最小订单金额
          name: '', //激励活动名称
          saveStatus: '', //保存状态 1-草稿 2-保存
          startTime: '', //活动开始时间
          userDailyNum: '', //每日用户参与次数
          userTotalNum: '', //用户参与总次数
        },
        rules: {
          areaId: [{
            required: true,
            message: "请选择管辖区域",
            trigger: ["change"]
          }],
          name: [{
            required: true,
            message: "请输入活动名称",
            trigger: ["change", "blur"]
          }],
          date: [{
            required: true,
            message: "请选择活动时间",
            trigger: ["change"]
          }],
          incentiveRule: [{
            required: true,
            message: "请选择激励规则",
            trigger: ["change"]
          }],
          incentiveType: [{
            required: true,
            message: "请选择积分类型",
            trigger: ["change"]
          }],
          limitOrderMoney: [{
            required: true,
            validator: inspectLimitOrderMoney,
            trigger: ['change', 'bulr'],
          }],
          incentiveValue: [{
            required: true,
            validator: inspectIncentiveValue,
            trigger: ['change', 'bulr'],
          }],
          dailyNum: [{
            required: true,
            validator: inspectDailyNum,
            trigger: ['change', 'bulr'],
          }],
          userDailyNum: [{
            required: true,
            validator: inspectUserDailyNum,
            trigger: ['change', 'bulr'],
          }],
          userTotalNum: [{
            required: true,
            validator: inspectUserTotalNum,
            trigger: ['change', 'bulr'],
          }],
          incentiveTopValue: [{
            required: true,
            validator: inspectIncentiveTopValue,
            trigger: ['change', 'bulr'],
          }],
        }
      }
    },
    computed: {

    },
    created() {
      this.getAdminDict()
      this.getAreaList()
      this.getTypels()
      this.type = this.$route.query.type

      if (this.type == 'add') { //新增
        this.getShopTempInit()
      } else if (this.type == 'edit') { //编辑
        this.ruleForm.id = this.$route.query.id
        this.queryParams.incentiveActivityId = this.$route.query.id
        this.getShopTempInit()
        this.getDatail()
      } else if (this.type == 'watch') { //查看
        this.ruleForm.id = this.$route.query.id
        this.getShopListWatch()
        this.getDatail()
      }
      this.getIndustrySelect()
    },
    methods: {
      //获取管辖区域下拉列表
      getAreaList() {
        areaList().then(res => {
          this.areaLs = res.result
        })
      },
      //获取字典
      getAdminDict() {
        var dictType = "shenye_incentive_rule,shenye_incentive_type";
        this.$getSelectList(dictType)
          .then((res) => {
            this.incentiveRuleLs = res.result[0].dictList; //激励规则
            this.incentiveTypeLs = res.result[1].dictList; //激励积分类型
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //初始化参与活动店铺临时表(新增、编辑的时候用)
      getShopTempInit() {
        var data = {
          incentiveActivityId: this.ruleForm.id
        }
        shopTempInit(data).then(res => {
          console.log('初始化成功')
          this.getList()
        })
      },
      /** 查询参与活动店铺临时列表（新增、编辑的时候查询） */
      getList() {
        console.log('获取列表')
        this.loading = true;
        shopTempList(this.queryParams).then(response => {
          this.tableList = response.result;
          // this.total = response.result.total;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        })
      },
      //查询参与活动店铺列表(watch,查看时查询)
      getShopListWatch() {
        this.loading = true;
        this.queryParams.incentiveActivityId = this.ruleForm.id
        shopListWatch(this.queryParams).then(response => {
          this.tableList = response.result;
          // this.total = response.result.total;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        })
      },
      // 获取行业类型
      getTypels() {
        this.loading = true;
        shopTypeTree()
          .then((res) => {
            this.typeLs = res.result;
            this.typeLs.forEach((item) => {
              item.children.forEach((items) => {
                if (items.children.length == 0) {
                  items.children = null
                }
              })
            })
          })
          .finally(() => {

          });
      },
      //行业选择
      handleChange(value) {
        let _this = this;
        console.log(value);
        if (value.length == 2) {
          _this.queryParams.shopTypeId = value[1];
          _this.queryParams.shopTypeParentId = value[0];
        } else {
          _this.queryParams.shopTypeParentId = value[0];
          _this.queryParams.shopTypeId = '';
        }
      },
      //获取神椰行业
      getIndustrySelect() {
        var params = {}
        industrySelect(params).then(res => {
          var arr = [{
            id: "",
            value: "全部",
          }, ];
          this.shenyeIndustryList = arr.concat(res.result)
        })
      },
      //获取详情
      getDatail() {
        incentiveActivityDetail(this.ruleForm.id).then(res => {
          this.ruleForm = {
            date: [res.result.startTime, res.result.endTime],
            areaId: res.result.areaId, //管辖区域id（新增必填）
            dailyNum: res.result.dailyNum, //每日活动名额
            endTime: res.result.endTime, //活动结束时间
            id: res.result.id, //激励活动id（编辑必填）
            incentiveRule: res.result.incentiveRule, //激励规则 1-按比例激励 2-固定金额激励 shenye_incentive_rule
            incentiveTopValue: res.result.incentiveTopValue, //封顶激励值
            incentiveType: res.result.incentiveType, //激励积分类型 1-CoCo 2-椰分 shenye_incentive_type	
            incentiveUserRule: res.result
              .incentiveUserRule, //用户规则 1-平台实名用户 2-当天实名用户 BeeShenyeIncentiveUserRuleEnum
            incentiveValue: res.result.incentiveValue, //激励比例/激励数额
            limitOrderMoney: res.result.limitOrderMoney, //最小订单金额
            name: res.result.name, //激励活动名称
            saveStatus: res.result.saveStatus, //保存状态 1-草稿 2-保存
            startTime: res.result.startTime, //活动开始时间
            userDailyNum: res.result.userDailyNum, //每日用户参与次数
            userTotalNum: res.result.userTotalNum, //用户参与总次数
          }
          this.status = res.result.status
        })
      },

      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.productIds = selection.map(item => item.id)
        console.log(this.productIds)
      },
      deleteView(id) { //删除
        let shopIdList = []
        if (id == null) {
          shopIdList = this.productIds
        } else {
          shopIdList = shopIdList.concat(id)
        }
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            shopIdList: shopIdList,
          }
          this.saveLoading = true
          activityShopTempDelete(data).then(response => {
            this.$message.success('删除成功!');
            this.getList()
          }).catch(() => {});
        }).catch();
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        if(this.type == 'watch'){
          this.getShopListWatch()
        }else{
          this.getList();
        }
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.shopTypeIdLs = []
        this.queryParams.pageNum = 1
        this.queryParams.keyword = ''
        this.queryParams.merchantLevel = ''
        this.queryParams.shenyeIndustryId = ''
        this.queryParams.shopTypeId = ''
        this.queryParams.shopTypeParentId = ''
        this.handleQuery();
      },
      areaChange() { //区域选择
        this.getShopTempInit()
      },
      /** 添加参与活动店铺列表 */
      addShopView() {
        // this.shopIdList = this.tableList.map((item) => {
        //   return item.shenyeShopId
        // })
        this.$refs.dialog.open(this.ruleForm.areaId, this.ruleForm.id);
      },
      //提交
      submitForm(formName, status) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (status == 1) {
              this.sumitLoadingOne = true
            } else {
              this.sumitLoading = true
            }
            this.ruleForm.saveStatus = status
            this.ruleForm.startTime = this.ruleForm.date[0] + ':' + '00'
            this.ruleForm.endTime = this.ruleForm.date[1] + ':' + '00'
            if (this.ruleForm.id == '') {
              var data = {
                ...this.ruleForm
              }
              shenyeIncentiveActivityAdd(data).then(res => {
                setTimeout(() => {
                  this.$message.success('创建成功')
                  this.$router.push({
                    path: 'incentiveActivities',
                  })
                  this.sumitLoading = false
                  this.sumitLoadingOne = false
                }, 800);
              }).catch(() => {
                this.sumitLoading = false
                this.sumitLoadingOne = false
              })
            } else {
              var data = {
                ...this.ruleForm
              }
              shenyeIncentiveActivityEdit(data).then(res => {
                setTimeout(() => {
                  this.$message.success('修改成功')
                  this.$router.push({
                    path: 'incentiveActivities',
                  })
                  this.sumitLoading = false
                  this.sumitLoadingOne = false
                }, 800);
              }).catch(() => {
                this.sumitLoading = false
                this.sumitLoadingOne = false
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) { //重置
        this.$refs[formName].resetFields();
      },

      //取消
      handleClose() {
        // this.$router.go(-1)
        this.$router.push({
          path: 'incentiveActivities',
        })
      },
    }
  }

</script>
<style lang="scss" scoped>
  .view-body {
    box-shadow: 0px 4px 12px 0px rgba(1, 41, 99, 0.06);
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px;
    margin: 20px;
  }

  .title_view {
    font-size: 15px;
    color: #1890ff;
    font-weight: bold;
    border-bottom: 1px solid #ddd;
    padding: 5px 0 16px 0;
    margin: 0 0 20px 0;
  }

  .el_table {
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 20px 10px 20px;
    margin: 20px 0 20px;
  }

</style>
